<template>
  <BasicModal
    @register="registerModal"
    v-bind="$attrs"
    :closeFunc="handleClose"
    :destroy-on-close="true"
  >
    <BasicForm @register="registerStepForm">
      <template #step="{ model, field }">
        <Steps :current="model[field]">
          <Step v-for="(item, index) in stepList" :key="index" :title="item.title" />
        </Steps>
      </template>
      <template #upload>
        <div class="flex justify-between">
          <Upload
            ref="inputRef"
            accept=".csv, .txt"
            :maxCount="1"
            :beforeUpload="handleBeforeUpload"
            @remove="handleRemove"
          >
            <a-button> 选择设备文件(CSV文件) </a-button>
          </Upload>
          <a-button
            type="primary"
            target="_blank"
            href="https://www-eio.upc.edu/~pau/cms/rdata/datasets.html"
          >
            <Icon :icon="ICON.INTERNET" />
            文件模板
          </a-button>
        </div>
      </template>
      <template #table>
        <BasicTable @register="registerTable" />
      </template>
      <template #loading>
        <div class="w-1000px h-50px">
          <Loading
            :loading="loading"
            :absolute="true"
            tip="加载中...请勿关闭！"
            :size="SizeEnum.SMALL"
            background="white"
          />
        </div>
      </template>
      <template #result>
        <Result status="success" title="上传成功" />
      </template>
    </BasicForm>
    <div class="flex flex-row justify-between">
      <a-button
        @click="backFunc"
        :disabled="currentStep == 0"
        v-show="currentStep != 3 && currentStep != 4"
      >
        后退
      </a-button>
      <a-button @click="continueFunc(fileData)" :disabled="!isContinue" v-show="currentStep != 3">
        {{ currentStep == 4 ? '完成' : '继续' }}
      </a-button>
    </div>
  </BasicModal>
</template>

<script setup lang="ts">
  import { ref } from 'vue';
  import { BasicTable, useTable } from '/@/components/Table';
  import { BasicForm, useForm } from '/@/components/Form';
  import { ICON } from '/@/enums/iconEnum';
  import { Icon } from '/@/components/Icon';
  import { Step, Steps, Result } from 'ant-design-vue';
  import { registerStepFormSchema, stepList, registerTableSchema } from './uploadDeviceModal.data';
  import { BasicModal, useModalInner } from '/@/components/Modal';
  import { Upload } from 'ant-design-vue';
  import { SizeEnum } from '/@/enums/sizeEnum';
  import { Loading } from '/@/components/Loading';
  import { processDevicesBulkImport } from '/@/api/thingsborad/entity/entity';
  import { importParams } from '/@/api/thingsborad/entity/model/entityModel';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { modalFormStyleSetting, modalStyleSetting } from '/@/settings/thingsBoardDesign';

  interface UploadFile {
    headers: Array<string>;
    rows: Array<Array<string>>;
  }
  const emit = defineEmits(['success']);

  const isContinue = ref(false);
  const currentStep = ref(0);
  const fileData = ref<File>();
  const csvContent = ref<any>();
  const loading = ref(true);
  const uploadResult = ref<UploadFile>({
    headers: [],
    rows: [],
  });
  const [registerTable, { setTableData, getDataSource }] = useTable({
    size: 'large',
    columns: registerTableSchema,
    pagination: false,
    striped: false,
    showIndexColumn: true,
    beforeEditSubmit: async () => {
      const tableData = getDataSource();
      let flag = 0;
      tableData.forEach((item) => {
        if (item.columnType == 'NAME' || item.columnType == 'TYPE') flag++;
      });
      if (flag == 2) {
        isContinue.value = true;
      } else {
        isContinue.value = false;
      }
      return true;
    },
  });
  const [registerStepForm, { resetFields, getFieldsValue, setFieldsValue }] = useForm({
    layout: 'vertical',
    labelWidth: 400,
    schemas: registerStepFormSchema,
    showActionButtonGroup: false,
    ...modalFormStyleSetting,
  });
  const [registerModal, { setModalProps, closeModal }] = useModalInner(async () => {
    loading.value = true;
    setModalProps({
      title: '导入设备',
      width: '800px',
      height: 600,
      showCancelBtn: false,
      showOkBtn: false,
      footer: null,
      maskClosable: false,
      ...modalStyleSetting,
    });
  });
  const { createMessage } = useMessage();
  // 上一步
  function backFunc() {
    const values = getFieldsValue();
    currentStep.value = Number(Number(values.currentStep) - 1);
    setFieldsValue({ currentStep: currentStep.value });
    isContinue.value = true;
  }
  // 下一步
  async function continueFunc(file?: any) {
    const values = getFieldsValue();
    currentStep.value = Number(Number(values.currentStep) + 1);
    setFieldsValue({ currentStep: currentStep.value });
    if (currentStep.value == 2) {
      uploadResult.value.headers = [];
      uploadResult.value.rows = [];
      const reader = new FileReader();
      reader.readAsText(file);
      reader.addEventListener('load', () => {
        try {
          csvContent.value = reader.result;
          csvContent.value.split('\n').forEach((element, index) => {
            if (values.containsColumn) {
              if (index == 0) {
                uploadResult.value.headers = element.trim().split(values.separator);
              } else {
                uploadResult.value.rows.push(element.trim().split(values.separator));
              }
            } else {
              if (index != 0) uploadResult.value.rows.push(element.trim().split(values.separator));
            }
          });
          let tableData: Recordable[] = [];
          if (values.containsColumn) {
            uploadResult.value.headers.forEach((item, index) => {
              if (item.toLowerCase() == 'name') {
                tableData.push({
                  exampleValue: uploadResult.value.rows[0][index],
                  columnType: 'NAME',
                  attribute: item,
                });
              } else if (item.toLowerCase() == 'type') {
                tableData.push({
                  exampleValue: uploadResult.value.rows[0][index],
                  columnType: 'TYPE',
                  attribute: item,
                });
              } else {
                tableData.push({
                  exampleValue: uploadResult.value.rows[0][index],
                  columnType: 'SERVER_ATTRIBUTE',
                  attribute: item,
                });
              }
            });
          } else {
            uploadResult.value.rows[0].forEach((item) => {
              tableData.push({
                exampleValue: item,
                columnType: 'SERVER_ATTRIBUTE',
                attribute: 'default',
              });
            });
          }
          setTableData(tableData);
          let flag = 0;
          uploadResult.value.headers.forEach((item) => {
            item.toLowerCase() == 'name' ? flag++ : '';
            item.toLowerCase() == 'type' ? flag++ : '';
          });
          if (flag == 2) {
            isContinue.value = true;
          } else {
            isContinue.value = false;
          }
        } catch (error) {
          createMessage.error('上传文件数据格式错误');
          isContinue.value = false;
        }
      });
    } else if (currentStep.value == 3) {
      const tableData = getDataSource();
      let columns: any = [];
      tableData.forEach((item) => {
        if (
          item.columnType == 'SHARED_ATTRIBUTE' ||
          item.columnType == 'TIMESERIES' ||
          item.columnType == 'SERVER_ATTRIBUTE'
        ) {
          columns.push({
            type: item.columnType,
            key: item.attribute,
          });
        } else {
          columns.push({
            type: item.columnType,
          });
        }
      });
      let params: importParams = {
        file: csvContent.value,
        mapping: {
          columns: columns,
          delimiter: values.separator,
          header: values.containsColumn,
          update: values.updateProperties,
        },
      };
      await processDevicesBulkImport(params);
      loading.value = false;
      currentStep.value = 4;
      setFieldsValue({ currentStep: currentStep.value });
    } else if (currentStep.value == 5) {
      closeModal();
      emit('success', { key: 'import' });
      return;
    }
  }
  // 选择文件
  function handleBeforeUpload(file: File) {
    fileData.value = file;
    isContinue.value = true;
    return false;
  }
  // 移除文件
  function handleRemove() {
    isContinue.value = false;
  }
  // 完成上传关闭弹窗
  async function handleClose() {
    await resetFields();
    return true;
  }
</script>
